package rabbit.flt.common.log;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;
import java.util.logging.*;

public class LogPrinter {

    private Logger realLogger;

    /**
     * ansi转移码
     */
    private String resetAnsi = "\u001B[0m";

    /**
     * ansi转移码
     */
    private String colorAnsi = "\u001B[30m";

    public LogPrinter(String name) {
        realLogger = Logger.getLogger(name);
        Logger rootLogger = Logger.getLogger("");
        for (Handler handler : rootLogger.getHandlers()) {
            // 移除根logger
            rootLogger.removeHandler(handler);
        }
        for (Handler handler : realLogger.getHandlers()) {
            if (handler instanceof ConsoleHandler) {
                // 如果添加了ConsoleHandler则直接返回
                return;
            }
        }
        // 添加自定义的处理器
        ConsoleHandler handler = new ConsoleHandler();
        handler.setLevel(Level.ALL);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        handler.setFormatter(new Formatter() {
            @Override
            public String format(LogRecord record) {
                return String.format("%s%s - %s: %s%s%n", colorAnsi, dateFormat.format(new Date()),
                        record.getLevel().getName(), record.getMessage(), resetAnsi);
            }
        });
        realLogger.addHandler(handler);
        realLogger.setLevel(Level.ALL);
    }

    public void info(String msg) {
        realLogger.info(msg);
    }


}
